import { LinkedList } from "./01_实现单向链表LinkedList";

class CircularLinkedList<T> extends LinkedList<T> {
  // 重写append方法
  append(value: T): void {
    super.append(value);
    // 修改最后一个节点的next指向头节点
    this.tail!.next = this.head;
  }
  // 重写insert方法
  insert(value: T, position: number): boolean {
    const isSuccess = super.insert(value, position);
    if ((isSuccess && position === this.length - 1) || position === 0) {
      // 修改最后一个节点的next指向头节点
      this.tail!.next = this.head;
    }
    return isSuccess;
  }
  // 重写removeAt方法
  removeAt(position: number): T | null {
    const value = super.removeAt(position);
    if (value && this.tail && (position === 0 || position === this.size - 1)) {
      // 修改最后一个节点的next指向头节点
      this.tail!.next = this.head;
    }
    return value;
  }
}

const circularLinkedList = new CircularLinkedList<string>();
circularLinkedList.append("a");
circularLinkedList.append("b");
circularLinkedList.append("c");
circularLinkedList.append("d");
circularLinkedList.traverse();

console.log("------- insert -------");
circularLinkedList.insert("x", 2);
circularLinkedList.insert("y", 0);
circularLinkedList.traverse();

console.log("------- removeAt -------");
circularLinkedList.removeAt(2);
circularLinkedList.removeAt(4);
circularLinkedList.removeAt(0);
circularLinkedList.traverse();

console.log("------- indexOf -------");
console.log(circularLinkedList.indexOf("x")); // 1

export {};
